package com.example.net

import com.example.common.SSLUtils
import com.example.common.TIMEOUT
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import org.apache.http.conn.ssl.AllowAllHostnameVerifier
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitFactory {
    //retrofit初始化
    private val retrofit : Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BuildConfig.SERVER_HOST)
            .addConverterFactory(GsonConverterFactory.create())
            .client(generateOkHttpClient())
            .build()
    }


    /**
     * 构建http对象
     */
    private fun generateOkHttpClient():OkHttpClient{
        val builder = OkHttpClient.Builder()
            .writeTimeout(TIMEOUT,TimeUnit.SECONDS)
            .callTimeout(TIMEOUT,TimeUnit.SECONDS)
            .readTimeout(TIMEOUT,TimeUnit.SECONDS)
            .connectTimeout(TIMEOUT,TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .sslSocketFactory(SSLUtils.getSslSocketFactory(),SSLUtils.getTrustManager())
            .hostnameVerifier(AllowAllHostnameVerifier())
            .addInterceptor(generateTokenInterceptor())
        if (BuildConfig.DEBUG){
            builder.addNetworkInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        }
        return builder.build()
    }


    /**
     * Token拦截器
     */
    private fun generateTokenInterceptor():Interceptor {
        return object :Interceptor{
            override fun intercept(chain: Interceptor.Chain): Response {
                return chain.proceed(chain.request())
            }
        }
    }

    /**
     * 创建api接口实例对象
     */
    fun <T> create(clazz:Class<*>):T{
        return retrofit.create(clazz) as T
    }

}